import config from "config";
import schema from "async-validator";
import { AppContext } from "ROOT/interface/App";
import SymbolOrderConfigService from "./SymbolOrderConfig.service";
import { traderRobot } from "ROOT/TraderRobot";
import SymbolOrderConfigEntity from "./SymbolOrderConfig.entity";

export default class SymbolOrderConfigController {
  public static index = async (ctx: AppContext) => {
    const { id } = ctx.request.query as Record<string, string>;
    const userId = ctx.state.user && ctx.state.user.id;
    try {
      if (id) {
        const res = await SymbolOrderConfigService.findOne({ id: Number(id)  });
        if (!res) {
          ctx.sendError({ message: "error" });
          return;
        }
        ctx.sendSuccess({
          data: {
            ...res,
          }
        });
      } else {
        const res = await SymbolOrderConfigService.find({ userid: userId }, false);

        res.forEach(item => {
          (item as any).watchCount =  traderRobot.getSymbolWatchCount(userId, item.symbol, item.trade_type)
        })
        ctx.sendSuccess({ data: res });
      }
    } catch (error) {
      ctx.sendError({ message: error });
    }
  };

  /**
   * 更新或者新建
   */
  public static updateOne = async (ctx: AppContext) => {
    const data = ctx.request.body as Record<string, any>;
    const validator = new schema({
      symbol: {
        type: "string",
        required: true
      },
      buy_usdt: {
        type: 'number'
      },
      sell_usdt: {
        type: 'number'
      },
      open_long: {
        type: "number"
      },
      open_short: {
        type: "number"
      },
      close_long: {
        type: "number"
      },
      close_short: {
        type: "number"
      },
      trade_type: {
        type: 'string',
        required: true
      },
      order_type: {
        type: 'string',
        required: true
      },
      config: {
        type: 'object'
      },
      // trade_ccount_id: {
      //   type: 'number',
      //   required: true
      // }
    });
    try {
      await validator.validate(data as any);
    } catch ({ errors, fields }) {
      ctx.sendError({ errors, message: errors[0] ? errors[0].message : undefined });
      return;
    }
    const userId = ctx.state.user && ctx.state.user.id;

    if (data.config.stopLoss === undefined) {
      Object.assign(data.config, {
        stopLoss: -0.2,
        stopProfit: 0.3,
        greedy: false
      })
    }
    try {
      let res: SymbolOrderConfigEntity;
   
      if (data.id) {
        const oldData = await SymbolOrderConfigService.findOne(
          { id: data.id },
        );
     
        res = await SymbolOrderConfigService.updateOne(
          { id: data.id },
          data
        );

        if (res.enabled) {
          traderRobot.addOrderConfig(res);
        } else if (oldData.enabled !== res.enabled && !res.enabled) {
          traderRobot.removeOrderConfig(userId, res.symbol);
        }
      } else if (data) {
        res = await SymbolOrderConfigService.create({
          ...data,
          userid: userId,
        });
        traderRobot.addOrderConfig(res);
      }    
      ctx.sendSuccess({
        data: res
      });
    } catch (error) {
      console.log(error)
      ctx.sendError({ message: error.message });
    }
  };

  /**
   * 删除单个
   */
  public static removeOne = async (ctx: AppContext) => {
    const data = ctx.request.body as Record<string, any>;
    const userId = ctx.state.user && ctx.state.user.id;
    const id = data.id;

    try {
      const res = await SymbolOrderConfigService.deleteOne({ id: id });
      traderRobot.removeOrderConfig(userId, res.symbol);
      ctx.sendSuccess({
        data: res
      });
    } catch (error) {
      ctx.sendError({ message: error });
    }
  };
    /**
   * 监听自己的订单风险
   */
    public static watchOrderRisk = async (ctx: AppContext) => {
      const data = ctx.request.body as Record<string, any>;
      const validator = new schema({
        id: {
          type: "number",
          required: true,
        },
      });
      try {
        await validator.validate(data);
      } catch ({ errors, fields }) {
        ctx.sendError({ errors });
        return;
      }
      const userId = ctx.state.user.id;
  
      try {
        const order = await SymbolOrderConfigService.findOne({ id: data.id });
        await traderRobot.trader.watchOrderRisk(userId, order.symbol, order.trade_type);
        ctx.sendSuccess({
          data: order
        });
      } catch (error) {
        ctx.sendError({ message: error });
      }
    }
}
